<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\adminService;

use think\Db;
use auth\Auth;
use think\Session;

class ProInvoice extends Common{
	//商家发票信息列表
	public function showlist(){
		$list=Db::table('pro_invoice')->select();
		$number=count($list);
		foreach ($list as $key => $value) {
			//根据商家id查询商家名称
			$info=Db::table("property")->find($value["property_id"]);
			$list[$key]["merchant_name"]=$info["merchant_name"];
		}
		$this->assign('list',$list);
		$this->assign('number',$number);
		return $this->fetch('proInvoice/showlist');
	}

	//添加商家发票
	public function add(){
		if(request()->isPost()){
			//获取表单数据
			$data = request()->post();
			//查询该商家是否已经添加
			$info=Db::table("pro_invoice")->find($data["property_id"]);
			if($info){
                $this->error('该商家已经存在');
            }
            $data["ctime"]=date('Y-m-d H:i:s');
            $result=Db::table('pro_invoice')->insert($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加商家成功',url('proInvoice/showlist'));
            }else{
                $this->error('添加商家失败',url('proInvoice/add'));
            }
		}else{
			$property = Db::table("property")->select();
        	$this->assign('property',$property);
			return $this->fetch('proInvoice/add');
		}
	}


	public function edit(){
		if(request()->isPost()){
			$data=request()->post();
			$result=Db::table('pro_invoice')->update($data);
			if($result){
                    $this->success('修改商家成功',url('proInvoice/showlist'));
            }else{
                    $this->error('修改商家失败');
            }
		}else{
			$id=request()->get('id');
			$info = Db::table("pro_invoice")->find($id);
			$property=Db::table("property")->find($info["property_id"]);
	        $info["merchant_name"]=$property["merchant_name"];
	        $this->assign('info',$info);
			return $this->fetch('proInvoice/edit');
		}	
	}

	public function del(){
		$id = request()->param('id');
        $validate = $this->validate(request()->param(),[
            'id'	=>	'require|number'
        ]);
        if($validate !== true){
            $this->error($validate);
        }
        //判断是否存在该数据
        $info = Db::name('pro_invoice')->where('id',$id)->find();
        if(empty($info)){
            $this->error('该商家不存在');
        }
        $result =  Db::table('pro_invoice')->delete($id);;
        if($result){
            $this->success('删除商家成功',url('proInvoice/showlist'));
        }else{
            $this->success('删除商家失败',url('proInvoice/showlist'));
        }	
	}
}